package com.tsinghua.discharge.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.tsinghua.discharge.common.Const;
import com.tsinghua.discharge.common.FileSolution;
import com.tsinghua.discharge.common.ServerResponse;
import com.tsinghua.discharge.dao.FileUploadRecordMapper;
import com.tsinghua.discharge.model.FileUploadRecord;
import com.tsinghua.discharge.model.User;
import com.tsinghua.discharge.service.FileUploadRecordService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class FileUploadRecordServiceImpl implements FileUploadRecordService {
    @Autowired
    private FileUploadRecordMapper fileuploadRecordMapper;

    @Autowired
    private FileSolution fileSolution;  //本地保存
    @Value("${spring.resources.static-locations}")
    private String path;
    public String getPath() {
        return path;
    }

    public ServerResponse addRecord(MultipartFile file, FileUploadRecord uploadRecord, HttpSession session){
        User currentUser = (User)session.getAttribute(Const.CURRENT_USER);
        Date now=new Date();
        String[] staticPath = getPath().split(",");
        String ownPath = staticPath[staticPath.length - 1];
        String root = ownPath.substring(ownPath.indexOf(':')+1);
        // String map = getMap().replaceAll("\\**","");
        String relativePath =  "UploadRecord/" + String.valueOf(currentUser.getUsername()) + "/";
        //map = map + relativePath;
        String path = root + relativePath;
        ServerResponse<String> resFile = fileSolution.uploadFile(file,path);
        if(!resFile.isSuccess()){
            return resFile;
        }
        FileUploadRecord addUploadRecord = new FileUploadRecord();
        addUploadRecord.setFileType(uploadRecord.getFileType());
        addUploadRecord.setFileName(file.getOriginalFilename());
        addUploadRecord.setFileUrl(path + resFile.getData());
        addUploadRecord.setCreateUserId(currentUser.getId());
        addUploadRecord.setFileCreateTime(now);
        addUploadRecord.setSector(uploadRecord.getSector());
        int affectedCount = fileuploadRecordMapper.insert(addUploadRecord);
        if(affectedCount > 0) {
            return ServerResponse.createBySuccess("添加成功");
        }
        return ServerResponse.createByErrorMessage("添加失败");



    }
    public ServerResponse addXlsxRecord(MultipartFile file, FileUploadRecord uploadRecord, HttpSession session){
        User currentUser = (User)session.getAttribute(Const.CURRENT_USER);
        Date now=new Date();
        String[] staticPath = getPath().split(",");
        String ownPath = staticPath[staticPath.length - 1];
        String root = ownPath.substring(ownPath.indexOf(':')+1);
        // String map = getMap().replaceAll("\\**","");
        String relativePath =  "UploadRecord/" + String.valueOf(currentUser.getUsername()) + "/";
        //map = map + relativePath;
        String path = root + relativePath;
        ServerResponse<String> resFile = fileSolution.uploadXlsxFile(file,path);
        if(!resFile.isSuccess()){
            return resFile;
        }
        FileUploadRecord addUploadRecord = new FileUploadRecord();
        addUploadRecord.setFileType(uploadRecord.getFileType());
        addUploadRecord.setFileName(file.getOriginalFilename());
        addUploadRecord.setFileUrl(path + resFile.getData());
        addUploadRecord.setCreateUserId(currentUser.getId());
        addUploadRecord.setFileCreateTime(now);
        addUploadRecord.setSector(uploadRecord.getSector());
        int affectedCount = fileuploadRecordMapper.insert(addUploadRecord);
        if(affectedCount > 0) {
            return ServerResponse.createBySuccess("添加成功");
        }
        return ServerResponse.createByErrorMessage("添加失败");



    }
    public ServerResponse<PageInfo> getList(Integer page, Integer limit, String fileType, HttpSession session) {
        PageHelper.startPage(page, limit);
        User currentUser = (User)session.getAttribute(Const.CURRENT_USER);
        List<FileUploadRecord> recordList = fileuploadRecordMapper.selectRecordList(currentUser.getId(),fileType);
        if(recordList.size() != 0){
            PageInfo<FileUploadRecord> pageResult = new PageInfo<>(recordList);
            return ServerResponse.createBySuccess(pageResult);
        }
        return ServerResponse.createByErrorMessage("获取上传记录失败");
    }
    public ServerResponse<PageInfo> getListBySector(Integer page, Integer limit, String fileType, HttpSession session,String sector) {
        User currentUser = (User)session.getAttribute(Const.CURRENT_USER);
        PageHelper.startPage(page, limit);
        List<FileUploadRecord> recordList = fileuploadRecordMapper.selectRecordBySector(currentUser.getId(),fileType,sector);
        if(recordList != null){
            PageInfo<FileUploadRecord> pageResult = new PageInfo<>(recordList);
            return ServerResponse.createBySuccess(pageResult);
        }
        return ServerResponse.createByErrorMessage("获取上传记录失败");
    }

    @Override
    public ServerResponse deleteRecordByFileTypeAndSector(String filetype,String sector, Integer userId) {
        List<FileUploadRecord> fileUploadRecord=fileuploadRecordMapper.selectRecordByFileTypeAndSector(filetype,sector,userId);

        for(FileUploadRecord record :fileUploadRecord) {
            ServerResponse resFile = fileSolution.deleteFile(record.getFileUrl());
            if(!resFile.isSuccess()){
                return resFile;
            }
        }
        int affectedCount = fileuploadRecordMapper.deleteByFileTypeAndSector(filetype,sector,userId);

        if(affectedCount > 0 ){
            return ServerResponse.createBySuccess("删除记录成功");
        }
        return ServerResponse.createByErrorMessage("删除记录失败");

    }
}
